package com.health.healthSys.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.health.common.core.domain.entity.SysUser;
import com.health.healthSys.domain.HealthDiet;
import com.health.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.healthSys.service.IHealthDietService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;

/**
 * 用户饮食记录Controller
 */
@RestController
@RequestMapping("/healthSys/diet")
public class HealthDietController extends BaseController {

    @Autowired
    private IHealthDietService healthDietService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询用户饮食记录列表
     */
    @PreAuthorize("@ss.hasPermi('healthSys:diet:list')")
    @GetMapping("/list")
    public TableDataInfo list(HealthDiet healthDiet) {
        startPage();
        List<HealthDiet> list = healthDietService.selectHealthDietList(healthDiet);
        return getDataTable(list);
    }

    /**
     * 导出用户饮食记录列表
     */
    @PreAuthorize("@ss.hasPermi('healthSys:diet:export')")
    @Log(title = "用户饮食记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HealthDiet healthDiet) {
        List<HealthDiet> list = healthDietService.selectHealthDietList(healthDiet);
        ExcelUtil<HealthDiet> util = new ExcelUtil<>(HealthDiet.class);
        util.exportExcel(response, list, "用户饮食记录数据");
    }

    /**
     * 获取用户饮食记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('healthSys:diet:query')")
    @GetMapping("/{dietId}")
    public AjaxResult getInfo(@PathVariable("dietId") String dietId) {
        return success(healthDietService.selectHealthDietByDietId(dietId));
    }

    /**
     * 新增用户饮食记录（管理端）
     */
    @PreAuthorize("@ss.hasPermi('healthSys:diet:add')")
    @Log(title = "用户饮食记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HealthDiet healthDiet) {
        completeUserInfo(healthDiet);
        return toAjax(healthDietService.insertHealthDiet(healthDiet));
    }

    /**
     * 修改用户饮食记录（管理端）
     */
    @PreAuthorize("@ss.hasPermi('healthSys:diet:edit')")
    @Log(title = "用户饮食记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HealthDiet healthDiet) {
        SysUser sysUser = sysUserService.selectUserById(healthDiet.getUserId());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        healthDiet.setUserName(sysUser.getUserName());
        return toAjax(healthDietService.updateHealthDiet(healthDiet));
    }

    /**
     * 用户自助修改记录
     */
    @PutMapping("/userEdit")
    public AjaxResult userEdit(@RequestBody HealthDiet healthDiet) {
        HealthDiet original = healthDietService.selectHealthDietByDietId(healthDiet.getDietId());
        if (original == null) {
            return AjaxResult.error("记录不存在");
        }
        Long currentUserId = getUserId();
        if (!original.getUserId().equals(currentUserId)) {
            return AjaxResult.error("无权修改他人记录");
        }
        healthDiet.setUserId(currentUserId);
        healthDiet.setUserName(getUsername());
        return toAjax(healthDietService.updateHealthDiet(healthDiet));
    }

    /**
     * 删除用户饮食记录
     */
    @PreAuthorize("@ss.hasPermi('healthSys:diet:remove')")
    @Log(title = "用户饮食记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dietIds}")
    public AjaxResult remove(@PathVariable String[] dietIds) {
        return toAjax(healthDietService.deleteHealthDietByDietIds(dietIds));
    }

    /**
     * 补全用户信息
     */
    private void completeUserInfo(HealthDiet healthDiet) {
        if (healthDiet.getUserId() == null) {
            healthDiet.setUserId(getUserId());
            healthDiet.setDeptId(getDeptId());
            SysUser currentUser = getLoginUser().getUser();
            healthDiet.setUserName(currentUser.getUserName());
        } else {
            SysUser user = sysUserService.selectUserById(healthDiet.getUserId());
            if (user != null) {
                healthDiet.setUserName(user.getUserName());
            }
        }
    }
}
